package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Division;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.User;
import com.sl.au.service.DivisionService;
import com.sl.au.service.GridAreaInfoService;
import com.sl.au.service.UserService;
import com.sl.utils.MsgHelper;

import scala.annotation.elidable;

/**
 * 用户 网格 区域详情
 * 
 * @author 何广川
 *
 */
@RestController
@RequestMapping("/ui/userGridDivison")
public class UserGridDivisionController extends BaseController {

	@Autowired
	private DivisionService divisionService;
	@Autowired
	private GridAreaInfoService gridAreaInfoService;
	@Autowired
	private UserService userService;
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@RequestMapping(value = "/unbind/{userIds}/{gridId}", method = RequestMethod.POST)
	public MsgHelper unbind(@PathVariable("userIds") String userIds, @PathVariable("gridId") String gridId) {

		// 之前绑定的用户
		GridAreaInfo gridAreaInfo = gridAreaInfoService.getRepository().findOne(gridId);
	//	Set<User> oldUsers = gridAreaInfo.getUsers();
		userIds = userIds.substring(0, userIds.length() - 1);

		String[] userIdArr = userIds.split(",");
		for (String g : userIdArr) {
			User findOne = userService.getRepository().findOne(g);
			Set<GridAreaInfo> grids = findOne.getGrids();
			grids.remove(gridAreaInfoService.getRepository().findOne(gridId));
			//findOne.setGrids(grids);
			userService.getRepository().save(findOne);
			/*if (oldUsers.size() > 0 && oldUsers != null) {
				for (User u : oldUsers) {
					if (u.getId().equals(findOne.getId())) {
						oldUsers.remove(findOne);
					}
				}
			}*/
		}
		/*gridAreaInfo.setUsers(oldUsers);
		gridAreaInfoService.getRepository().save(gridAreaInfo);*/
		return MsgHelper.success();
	}

	@RequestMapping(value = "/bind/{gridId}/{userIds}", method = RequestMethod.GET)
	public MsgHelper bind(@PathVariable("userIds") String userIds, @PathVariable("gridId") String gridId) {
		userIds = userIds.substring(0, userIds.length() - 1);
	//	List<String> gridIds=new ArrayList<>();
	//	Set<GridAreaInfo>gridAreaInfos=new LinkedHashSet<>(gridAreaInfoService.getRepository().findAll(gridIds));
	//	gridIds.add(gridId);
		// 当前网格之前绑定的用户
		GridAreaInfo gridAreaInfo = gridAreaInfoService.getRepository().findOne(gridId);
		Set<User> oldUsers = gridAreaInfo.getUsers();
		String[] userIdArr = userIds.split(",");
		for (String g : userIdArr) {
			User findOne = userService.getRepository().findOne(g);
	//		findOne.setGrids(gridAreaInfos);
			Set<GridAreaInfo> gridAreaInfos = findOne.getGrids();
			gridAreaInfos.add(gridAreaInfo);
			findOne.setGrids(gridAreaInfos);
			//oldUsers.add(findOne);
			userService.getRepository().save(findOne);

		}
		//gridAreaInfo.setUsers(oldUsers);
		//gridAreaInfoService.getRepository().save(gridAreaInfo);
		
		return MsgHelper.success();
	}

	/**
	 * <pre>
		select uu.id as id, uu.`name` as name  from sl_au_user uu where uu.id not IN
		 (
			SELECT ug.user_id from sl_wcsi_user_grid ug
		 )
	  
		select count(*) count from sl_au_user uu where uu.id not IN
		(
			SELECT ug.user_id from sl_wcsi_user_grid ug
		)
	 * </pre>
	 * 
	 * 获取没有绑定网格的用户信息
	 * 
	 */
	@RequestMapping(value = "/getUnbindUserPage", method = RequestMethod.POST)
	public Map<String, Object> getUnbindUserPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String gid = request.getParameter("gid");
		List<User> users = new ArrayList<>();
		int count = 0;
		if (StringUtils.hasText(gid)) {
			StringBuilder sb = new StringBuilder();
			StringBuilder sb2 = new StringBuilder();
			String sql = "select uu.id as id, uu.`name` as name" //
					+ " from sl_au_user uu where uu.id not IN" //
					+ "(SELECT ug.user_id from sl_wcsi_user_grid ug where ug.grid_id='"+gid+"')";
			if (StringUtils.hasText(key)) {
				sb.append(" and( uu.name like '%" + key + "%')");
				sb2.append(" and( uu.name like '%" + key + "%')");
			}
			sb.append(" limit " + start + "," + length);
			sql = sql + sb.toString();
			List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

			int i = 0;
			String id = "";
			String name = "";
			for (Map<String, Object> m : list) {

				User u = new User();
				Set<String> keys = m.keySet();
				for (String s : keys) {
					++i;
					if ("id".equals(s)) {
						id = m.get(s).toString();
						// u.setId(m.get(s).toString());
					}
					if ("name".equals(s)) {
						name = m.get(s).toString();
						// u.setName(m.get(s).toString());
					}
					if (i % 2 == 0) {
						u.setId(id);
						u.setName(name);
						users.add(u);
						i = 0;
					}

				}
			}

			sql = "select count(*) count from sl_au_user uu"//
					+ " where uu.id not IN(SELECT ug.user_id from sl_wcsi_user_grid ug where ug.grid_id='"+gid+"')";

			sql = sql + sb2.toString();

			List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
			for (Map<String, Object> m : queryForList) {
				Set<String> keySet = m.keySet();
				for (String s : keySet) {
					if ("count".equals(s)) {
						count = Integer.parseInt(m.get(s).toString());
					}
				}
			}
		}


		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 绑定了网格的用户信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getBindUserPage", method = RequestMethod.POST)
	public Map<String, Object> getBindUserPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");// gridId
		String con = request.getParameter("con");// gridId

		List<User> users = null;
		int count = 0;
		if (StringUtils.hasText(con)) {
			users = userService.getBindUsersPageByKeyAndCon(start, length, key, con);
			count = userService.getBindUserCountByCon(key, con);
		} else {
			users = userService.getBindUsersPage(start, length, key, null, null);
			count = userService.getBindUserCount(key);
		}

		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 获取各种条件下的网格信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getGridPage", method = RequestMethod.POST)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");// 传递的区域ID
		String con = request.getParameter("con");
		List<GridAreaInfo> areaInfos = null;
		Integer count = null;
		if (!"0".equals(key)) {
			// 查询指定区域的网格
			if (StringUtils.hasText(con)) {
				areaInfos = gridAreaInfoService.findBindDivisionPageByKeyAndCon(key, con, start, length);
				count = gridAreaInfoService.findBindDivisionCountByKeyAndCon(key, con, start, length);
			} else {
				areaInfos = gridAreaInfoService.findBindDivisionPageOnlyKey(key, con, start, length);
				count = gridAreaInfoService.findBindDivisionCountOnlyKey(key, con, start, length);
			}
		} else {
			if (StringUtils.hasText(con)) {
				areaInfos = gridAreaInfoService.findBindDivisionPageOnlyCon(con, start, length);
				count = gridAreaInfoService.findBindDivisionCountOnlyCon(key, con, start, length);
			} else {
				areaInfos = gridAreaInfoService.findBindDivisionPageNone(start, length);
				count = gridAreaInfoService.findBindDivisionCountNone(start, length);
			}
		}
		
		map.put("data", areaInfos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "getAllNodes", method = RequestMethod.GET)
	public Map<String, Object> getAllNodes(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Division> node = null;
		node = divisionService.getAllNodes();
		List<Map<String, Object>> nodeMap = new ArrayList<Map<String, Object>>();

		nodeMap = divisionService.getNodeMap(node);

		map.put("code", 1);
		map.put("nodes", nodeMap);

		return map;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {
		modelAndView = createLayoutView("userGridDivision/index");
		return modelAndView;
	}
}
